package com.gcms.controller.base;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

@RestController
@RequestMapping("/file")
@Slf4j
public class FileController {


    private final static String endpoint = "https://oss-cn-beijing.aliyuncs.com";

    private final static String accessKeyId = "LTAI5tNvaiQNMa2ub9H7akmk";

    private  final static String accessKeySecret = "Mvoige3s9uhrbMaZnP8mYqnrEZM4gv";


    @PostMapping("/upload")
    @ResponseBody
    public String uploadFile(@RequestParam("file") MultipartFile file) {

        String bucketName = "zy-sea-biology-classify";

        String originalFilename = file.getOriginalFilename();
        OSS ossClient
                = new OSSClientBuilder()
                .build(endpoint, accessKeyId, accessKeySecret);

        if (originalFilename != null) {
            String fileName = UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));

            try (InputStream inputStream = file.getInputStream()) {

                ossClient.putObject(bucketName, fileName, inputStream);

                // 获取文件访问地址
                return "https://" + bucketName + "." + endpoint.substring(endpoint.lastIndexOf("/")+1)+"/"+ fileName;

            } catch (Exception e) {
                log.error("图片上传失败,异常信息为{}",e.getMessage());
                return "上传失败";
            }finally {
                // 关闭OSSClient
                ossClient.shutdown();
            }

        }


        return "上传失败";


    }

}
